//
//  MZ_AppleLoginManager.m
//  MZ
//
//  Created by mr_huang on 2021/12/21.
//  Copyright © 2021 MZ_. All rights reserved.
//

#import "MZ_AppleLoginManager.h"


@interface MZ_AppleLoginManager ()<ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>
@property (nonatomic, copy)void (^successBlock)(NSString *userId,NSData * token);

@property (nonatomic, copy)void (^failureBlock)(NSString *errStr);

@end

@implementation MZ_AppleLoginManager


+(instancetype)shareInstance {
    static MZ_AppleLoginManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[MZ_AppleLoginManager alloc]init];
    });
    return instance;
}
- (void)loginWithAppleSuccess:(void (^)(NSString *appleId,NSData * token))successBlock failure:(void (^)(NSString *))failureBlock
{
    self.successBlock = successBlock;
    self.failureBlock = failureBlock;
    [self onClickBeginSignWithApple];
}
- (void)onClickBeginSignWithApple
{
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *appleIDProvider = [ASAuthorizationAppleIDProvider new];
        ASAuthorizationAppleIDRequest *request = appleIDProvider.createRequest;
        [request setRequestedScopes:@[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail]];
        
        //需要考虑已经登录过的用户，可以直接使用keychain密码来进行登录-这个很牛皮。。。
//        ASAuthorizationPasswordProvider *appleIDPasswordProvider = [ASAuthorizationPasswordProvider new];
//
//        ASAuthorizationPasswordRequest *passwordRequest = appleIDPasswordProvider.createRequest;
        
        ASAuthorizationController *appleSignController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        appleSignController.delegate = self;
        appleSignController.presentationContextProvider = self;
        [appleSignController performRequests];
    } else {
        // Fallback on earlier versions
    }

}

- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    return [Manager SQ_getCurrentViewController].view.window;
}
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error  API_AVAILABLE(ios(13.0)){
    //Sign with Apple 失败
    NSString * errorMsg = nil;
        
        switch (error.code) {
                case ASAuthorizationErrorCanceled:
                errorMsg = @"用户取消了授权请求";
                break;
                case ASAuthorizationErrorFailed:
                errorMsg = @"授权请求失败";
                break;
                case ASAuthorizationErrorInvalidResponse:
                errorMsg = @"授权请求响应无效";
                break;
                case ASAuthorizationErrorNotHandled:
                errorMsg = @"未能处理授权请求";
                break;
                case ASAuthorizationErrorUnknown:
                errorMsg = @"授权请求失败未知原因";
                break;
        
        }
    !self.failureBlock ? : self.failureBlock(errorMsg);
}
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
        //Sign with Apple 成功
   if ([authorization.provider isKindOfClass:[ASAuthorizationAppleIDProvider class]]) {
                        //此时为使用Sign With Apple 方式登录
                          //继续进行客户端后台登录验证
       ASAuthorizationAppleIDCredential * credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
       
       !self.successBlock ? : self.successBlock(credential.user,credential.identityToken);

//       userIdentifier
        }
}
@end
